import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core';
import { ApesFormatEmitEvent } from '@shared/apes/core';

@Component({
  selector: 'epc-tree-menu',
  template: `
    <apes-tree [apesData]="treeNodes" (apesClick)="onSelect($event)"></apes-tree>
  `,
})
export class EpcTreeMenuComponent implements OnInit, OnChanges {
  @Input() isLoading: boolean = false;
  @Input() nodes;
  @Output() selected = new EventEmitter();

  treeNodes = [];

  ngOnInit(): void {
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.nodes) {
      let nodes = this.resolveData(changes.nodes.currentValue);
      this.treeNodes = Object.keys(nodes).length == 0 ? [] : nodes;
    }
  }

  resolveData(param) {
    for (let i = 0, len = param.length; i < len; i++) {
      let tempJson = param[i];
      tempJson.key = tempJson.id;
      tempJson.title = tempJson.name;
      if (tempJson.children && tempJson.children.length > 0) {
        tempJson.selectable = false;
        this.resolveData(tempJson.children);
      } else {
        tempJson.isLeaf = true;
      }
    }
    return param;
  }

  onSelect(event: ApesFormatEmitEvent) {
    // 选择为叶子节点的时候触发
    if( event.node.isLeaf && !this.isLoading ) {
      this.selected.emit(event.node.origin);
    }
  }
}
